package com.itqf.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itqf.entity.ScheduleJob;
import com.itqf.mapper.ScheduleJobMapper;
import com.itqf.service.ScheduleJobService;
import com.itqf.utils.R;
import com.itqf.utils.SchedulerUtils;
import com.itqf.utils.SysConstant;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Description:
 * @Company: 千锋互联
 * @Author: 李丽婷
 * @Date: 2020/10/21
 * @Time: 上午9:22
 */
@Service
public class ScheduleJobServiceImpl implements ScheduleJobService {

    @Resource
    private ScheduleJobMapper scheduleJobMapper;

    //注入Scheduler
    @Resource
    private Scheduler scheduler;//com.itqf.config  @Bean

    /**
     * bootstrap-table  分页查询  需要的json格式
     * {total:xx,rows:[{},{}]}   easyui
     * @param limit
     * @param offset
     * @param search
     * @param order
     * @return
     */
    @Override
    public R scheduleJobList(int limit, int offset, String search, String order) {

        long current = offset/limit+1;
        //Page(long current, long size)
       IPage<ScheduleJob> scheduleJobIPage = new Page<>(current,limit);
        QueryWrapper queryWrapper  = null;

        if (search!=null&&!search.equals("")){
            queryWrapper =  new QueryWrapper();
            queryWrapper.like("beanName",search);
        }
        if (order!=null){
            if (queryWrapper==null) {
                queryWrapper = new QueryWrapper();
            }
            if (order.equalsIgnoreCase("desc")){
                queryWrapper.orderByDesc("job_id");
            }else{
                queryWrapper.orderByAsc("job_id");
            }
        }

        // //IPage<T> var1, @Param("ew") Wrapper<T> var2
       IPage<ScheduleJob> iPage =  scheduleJobMapper.selectPage(scheduleJobIPage,queryWrapper);

        long total = iPage.getTotal();
        List<ScheduleJob> rows = iPage.getRecords();

        return R.ok().put("total",total).put("rows",rows);
    }

    @Override
    public R saveScheduleJob(ScheduleJob scheduleJob) {
        //1,操作数据库  plus
        System.out.println("新增前:"+scheduleJob.getJobId());
        scheduleJob.setCreateTime(new Date());
        int i = scheduleJobMapper.insert(scheduleJob);
        System.out.println("新增后，plus把自增主键返回给参数的主键属性"+scheduleJob.getJobId());
        //1)<selectKey>   2) usegeneratorKeys="true"
        //2.quartz来创建Task
        SchedulerUtils.createTask(scheduleJob,scheduler);

        return i>0?R.ok():R.error();
    }

    @Override
    public R updateScheduleJob(ScheduleJob scheduleJob) {
        UpdateWrapper wrapper = new UpdateWrapper();
        wrapper.eq("job_id",scheduleJob.getJobId());
        //1,操作数据库
        int i = scheduleJobMapper.update(scheduleJob,wrapper);
        //2.quartz修改Task
        SchedulerUtils.update(scheduler,scheduleJob);


        return i>0?R.ok():R.error();    }

    @Override
    public R deleteScheduleJob(List<Long> ids) {
        //1.批量删除数据库 schedule_job表中的记录
        int i =  scheduleJobMapper.deleteBatchIds(ids);
        System.out.println(i+""+ids);
        List<JobKey> list = new ArrayList<>();
        for (Long id : ids) {
            JobKey key = JobKey.jobKey(SysConstant.JOB_PREFIX+id);
            list.add(key);
        }
        //2.批量删除真正的任务
        SchedulerUtils.delete(scheduler,list);

        return i>0?R.ok():R.error();    }

    /**
     * 暂停  status:  0:暂停  1:恢复
     * @param ids
     * @return
     */
    @Override
    public R pauseScheduleJob(List<Long> ids) {
        ScheduleJob scheduleJob = new ScheduleJob();
        scheduleJob.setStatus(SysConstant.JOB_PAUSE);
        UpdateWrapper updateWrapper = new UpdateWrapper();
        updateWrapper.in("job_id",ids);

        int i =  scheduleJobMapper.update(scheduleJob,updateWrapper);

        //2.批量暂停真正的任务
        for (Long id : ids) {
            SchedulerUtils.pause(scheduler,id);
        }

        return i>0?R.ok():R.error();
    }

    /**
     * 恢复
     * @param ids
     * @return
     */
    @Override
    public R resumeScheduleJob(List<Long> ids) {
        ScheduleJob scheduleJob = new ScheduleJob();
        scheduleJob.setStatus(SysConstant.JOB_RESUME);
        UpdateWrapper updateWrapper = new UpdateWrapper();
        updateWrapper.in("job_id",ids);

        int i =  scheduleJobMapper.update(scheduleJob,updateWrapper);

        //2.批量恢复真正的任务
        for (Long id : ids) {
            SchedulerUtils.resume(scheduler,id);
        }
        return i>0?R.ok():R.error();
    }

    /**
     * 运行一次
     * @param ids
     * @return
     */
    @Override
    public R runOneScheduleJob(List<Long> ids) {
        for (Long id : ids) {
            SchedulerUtils.runOnce(scheduler,id);

        }
        return R.ok();
    }

    @Override
    public R scheduleInfo(long id) {
        //
        ScheduleJob scheduleJob = scheduleJobMapper.selectById(id);

        return R.ok().put("scheduleJob",scheduleJob);
    }
}
